var api = require('../../utils/api.js');
var app = getApp();
Page({
  data: {
    imgUrls: [],
    indicatorDo: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    swiperCurrent: 0,
    phone: '',
    user_id: '',//用户ID
    name: '',//免费试听 - 姓名
    mobile: '', //免费试听 - 手机号
    logo: [],
    /**
     * 选择城市
     */
    city: [],
    objectCity: [],
    city_value: 0,
    aid: '',
    /**
     * 选择年级
     */
    grade: [],
    objectGrade: [],
    grade_value: 0,
    grade_id: '',
    /**
     * 选择科目
     */
    subject: [],
    objectSubject: [],
    subject_value: 0,
    subject_id: '',
    /**
     * 是否为老学员
     */
    cadets: [],
    objectCadets: [],
    cadets_value: 0,
    cadets_id: '',

    systemInfo: {},
    _api: {},
    list: [],//推荐课程
    total: 0,
    loadingMore: false,
    noMoreData: false,
    searchInputShowed: false,
    searchInputVal: "",
    searchingResult: false,
    searchKeyword: "",
    search_text_length: 0,
    keyword: '',
    pwd: '',//视频密码
    has_pwd: false,// false没有密码 true有密码
    verify_pwd: false,//判断输入密码是否正确
    focus: true,
    wx_imgUrls: [],
    keyword: [],
  },
  currentPageNumber: 1,

  // 填写姓名
  bindInputName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },

  // 轮播图切换图标
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  // 填写手机号
  bindInputMobile: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },

  // 选择城市
  select_city: function (e) {
    var index = e.detail.value
    var aid = this.data.objectCity[index].aid
    console.log(aid)
    this.setData({
      aid: aid,
      city_value: index
    })
  },
  // 选择年级
  select_grade: function (e) {
    var index = e.detail.value
    var grade_id = this.data.objectGrade[index].id
    console.log(grade_id)
    this.setData({
      grade_id: grade_id,
      grade_value: index
    })
  },
  // 选择科目
  select_subject: function (e) {
    var index = e.detail.value
    var subject_id = this.data.objectSubject[index].id
    console.log(subject_id)
    this.setData({
      subject_id: subject_id,
      subject_value: index
    })
  },

  // 是否老会员
  select_cadets: function (e) {
    var index = e.detail.value
    var cadets_id = this.data.objectCadets[index].id
    console.log(cadets_id)
    this.setData({
      cadets_id: cadets_id,
      cadets_value: index
    })
  },


  // 拨打电话
  call_phone: function (e) {
    wx.makePhoneCall({
      phoneNumber: this.data.phone
    })
  },


  onLoad() {
    api.get({
      url: 'wxapp/product/getLogo',
      data: {
      },
      success: data => {
        this.setData({
          logo: data.data
        });
      }
    });
    try {
      var isLogin = wx.getStorageSync('login');
      if (!isLogin) {
        api.login();
        return;
      }
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      _api: api,
    });
  },


  onShow() {
    console.log(app.pagesNeedUpdate);
    if (app.pagesNeedUpdate['pages/index/index'] == 1) {
      let newItems = api.updatePageList('id');
      console.log(newItems);
      this.setData({
        list: newItems
      });
    }

    if (app.pagesNeedUpdate['pages/index/index'] == 'refresh') {
      this.onPullDownRefresh();
    }
    this.pullUpLoad();

    api.pageNeedUpdate('pages/index/index', 0);
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.currentPageNumber = 1;
    this.setData({
      noMoreData: false,
      noData: false
    });
    api.get({
      url: 'portal/articles/wx_index',
      data: {
        order: '-published_time'
      },
      success: data => {
        let newItems = api.updatePageList('id', data.data, this.formatListItem, true);
        console.log(newItems);
        this.setData({
          list: newItems
        });

        if (data.data.length > 0) {
          this.currentPageNumber++;
        } else {
          this.setData({
            noMoreData: true
          });
        }

        wx.stopPullDownRefresh();
      }
    });
  },

  /**
   * 上拉刷新
   */
  pullUpLoad() {
    if (this.data.loadingMore || this.data.noMoreData) return;
    var user = wx.getStorageSync('user');//用户信息
    this.setData({
      user_id: user.id,
      loadingMore: true
    });
    wx.showNavigationBarLoading();

    api.get({
      url: 'portal/articles/wx_index',
      data: {
        page: this.currentPageNumber,
        order: '-published_time'
      },
      success: data => {
        let newItems = api.updatePageList('id', data.data, this.formatListItem);
        console.log(newItems);
        this.setData({
          list: newItems
        });
        if (data.data.length > 0) {
          this.currentPageNumber++;
        } else {
          this.setData({
            noMoreData: true
          });
        }
      },
      complete: () => {
        this.setData({
          loadingMore: false
        });
        wx.hideNavigationBarLoading();
      }
    });

    api.get({
      url: 'wxapp/Index/formData',
      success: data => {
        var cityarr = []
        for (var i = 0; i < data.city.length; i++) {
          cityarr.push(data.city[i].area_name)
        }

        var gradearr = []
        for (var i = 0; i < data.grade.length; i++) {
          gradearr.push(data.grade[i].name)
        }

        var subjectarr = []
        for (var i = 0; i < data.course.length; i++) {
          subjectarr.push(data.course[i].name)
        }

        var cadetstarr = []
        for (var i = 0; i < data.cadets.length; i++) {
          cadetstarr.push(data.cadets[i].name)
        }

        this.setData({
          aid: data.city[0].aid,
          objectCity: data.city,
          city: cityarr,

          grade_id: data.grade[0].id,
          objectGrade: data.grade,
          grade: gradearr,

          subject_id: data.course[0].id,
          objectSubject: data.course,
          subject: subjectarr,

          cadets_id: data.cadets[0].id,
          objectCadets: data.cadets,
          cadets: cadetstarr
        })
      }
    });

    api.get({
      url: 'wxapp/Index/Ad',
      data: {
        id: 2
      },
      success: res => {
        this.setData({
          imgUrls: res
        })
      }
    });

    api.get({
      url: 'wxapp/Index/Ad_wx',
      data: {},
      success: res => {
        this.setData({
          wx_imgUrls: res
        })
      }
    })
  },
  formatListItem(item) {
    if (item.Thumbnail) {
      item.Thumbnail = api.getUploadUrl(item.Thumbnail);
    }
    return item;
  },
  onReachBottom() {
    // this.pullUpLoad();
  },
  onListItemMoreTap(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/article/article?id=' + id
    });
  },

  // 获取收拾框输入的文本内容
  search_txt(e) {
    this.setData({
      keyword: e.detail.value,
      search_text_length: e.detail.value.length
    })
  },

  showSearchInput() {
    this.setData({
      searchInputShowed: true,
      searchingResult: false
    });
  },
  hideSearchInput() {
    this.setData({
      searchInputVal: "",
      searchKeyword: "",
      searchInputShowed: false,
      searchingResult: false
    });
    this.onPullDownRefresh();
  },
  clearSearchInput() {
    this.setData({
      searchInputVal: "",
      searchKeyword: "",
      searchingResult: false
    });
    this.onPullDownRefresh();
  },
  searchInputTyping(e) {
    this.setData({
      searchInputVal: e.detail.value,
      searchKeyword: "",
      searchingResult: false
    });
  },
  searchSubmit() {
    this.setData({
      searchingResult: true,
      searchKeyword: this.data.searchInputVal
    });
    this.onPullDownRefresh();
  },
  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.src] // 需要预览的图片http链接列表
    });
  },
  //分享
  onShareAppMessage(e) {
    let user_id = this.data.user_id
    return {
      path: '/pages/index/index',
      success: function (res) {
        api.post({
          url: 'wxapp/Index/share',
          data: {
            title: '首页',
            user_id: user_id
          },
          success: res => {
            wx.showToast({
              title: res.msg,
              icon: 'success',
              duration: 2000
            })
          }
        })
      },
    }
  },


  /**
   * 搜索微课堂
   * code=1 有查到相关数据
   * code=0 暂无相关数据
   */
  searchLesson(e) {
    let keyword = this.data.keyword
    api.post({
      url: 'wxapp/Index/searchLesson_recommend',
      data: {
        keyword: keyword
      },
      success: data => {
        if (data.code == 1) {
          this.setData({
            list: data.data
          });
        } else if (data.code == 0) {
          wx.showToast({
            title: data.msg,
            image: '/images/icons/fail2.png',
            duration: 2000
          })
          return false;
        }
      }
    })
  },

  //领取免费试听
  freeUse() {
    if (!this.data.name) {
      wx.showToast({
        title: '请输入姓名',
        image: '/images/icons/fail2.png',
        duration: 2000
      })
      return false;
    }

    //正则表达式验证手机号是否正确
    var myreg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[3|6|7|8]|18[0-9])\d{8}$/;
    if (!myreg.test(this.data.mobile)) {
      wx.showToast({
        title: '手机号不正确',
        image: '/images/icons/fail2.png',
        duration: 2000
      })
      return false;
    }

    api.post({
      url: 'wxapp/Index/freeJoin',
      data: {
        user_id: this.data.user_id, //用户ID
        name: this.data.name, //姓名
        city: this.data.aid, //城市
        grade: this.data.grade_id, //年级
        course: this.data.subject_id, //课程
        is_old: this.data.cadets_id, //是否为老学员
        mobile: this.data.mobile, //手机号
      },
      success: data => {
        wx.showToast({
          title: data.msg,
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
  //弹出框 取消按钮
  onCancel: function () {
    this.setData({
      has_pwd: false,
      focus: true,
    });
  },
  //弹出框 确定按钮
  onConfirm() {
    var that = this;

    if (this.data.pwd_input == this.data.pwd) {
      this.setData({
        has_pwd: false,
        focus: true,
      });
      wx.navigateTo({
        url: '/pages/article/article?id=' + this.data.art_id
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '密码错误',
        showCancel: false,
        success: function (res) {
      
          if (res.confirm) {
            that.setData({
              has_pwd: true,
              focus: true
            })
          }
        }
      })
      return
    }
  },
  priceInput(e) {
    this.setData({
      pwd_input: e.detail.value
    })
  },
  onListItemTap(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/article/article?id=' + id
    });
    //判断该课程是否有密码
    // api.post({
    //   url: 'wxapp/Index/isset_pwd',
    //   data: {
    //     id: id
    //   },
    //   success: res => {
    //     if (res.data.post_pwd) {
    //       this.setData({
    //         art_id: id,
    //         pwd: res.data.post_pwd,
    //         has_pwd: true
    //       })
    //     } else {
    //       wx.navigateTo({
    //         url: '/pages/article/article?id=' + id
    //       });
    //     }
    //   }
    // })
  },

  goNewPage(e) {
    let go_url = e.currentTarget.dataset.url

    if (go_url > 0) {
      wx.navigateTo({
        url: '/pages/public/public?url=' + go_url
      })
    }
  }
});
